package com.enqualcomm.kids.component;

import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.ResultReceiver;
import android.os.SystemClock;

import com.android.volley.socket.MultiRequest;
import com.android.volley.socket.SocketAddressSwitcher;
import com.android.volley.socket.SocketClient;
import com.android.volley.socket.SocketNetwork;
import com.enqualcomm.kids.component.command.BaseCommand;
import com.enqualcomm.kids.component.command.LoadPicCommand;
import com.enqualcomm.kids.config.Constants;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.config.userdefault.TerminalDefault;
import com.enqualcomm.kids.config.userdefault.UserDefault;
import com.enqualcomm.kids.config.userdefault.UserTerminalDefault;
import com.enqualcomm.kids.manager.Controller;
import com.enqualcomm.kids.network.socket.request.GetAccessToken;
import com.enqualcomm.kids.network.socket.request.GetAllTerminalConfig;
import com.enqualcomm.kids.network.socket.request.LoginParams;
import com.enqualcomm.kids.network.socket.request.QueryUserTerminalInfoParams;
import com.enqualcomm.kids.network.socket.request.TerminalConfigParams;
import com.enqualcomm.kids.network.socket.request.TerminalListParams;
import com.enqualcomm.kids.network.socket.response.AllTerminalConfig;
import com.enqualcomm.kids.network.socket.response.LoginResult;
import com.enqualcomm.kids.network.socket.response.QueryUserTerminalInfoResult;
import com.enqualcomm.kids.network.socket.response.TerminalConfigResult;
import com.enqualcomm.kids.network.socket.response.TerminallistResult;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import common.utils.GsonFactory;
import common.utils.MyLogger;
import common.utils.NetUtil;
import common.utils.PlatformUtil;

/**
 * Created by yinzhiqun on 2015/8/26.
 * <p>
 * 初始化运行环境，获取一些必要的数据
 */
public class InitContextIntentService extends IntentService {
    public static final String RECEIVER = "RECEIVER";
    /**
     * 获取数据成功
     */
    public static final int SUCCESS = 200;
    /**
     * 密码错误
     */
    public static final int PASSWORD_WRONG = 304;

    private ResultReceiver mReceiver;

    private int count;

    public InitContextIntentService() {
        super("InitContextIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        mReceiver = intent.getParcelableExtra(RECEIVER);
        AppDefault appDefault = new AppDefault();

        SocketNetwork network = SocketClient.initSocketNetwork(this);
        count = 0;
        while (PlatformUtil.isRunningForeground(this)) {//如果应用已经退出，应该结束掉
            if (NetUtil.checkNet(this)) {//如果没有获取到，等待网络正常后继续
                try {
                    FirstRequest request = new FirstRequest();
                    network.performMultiRequest(request);
                    save(request, appDefault);
                    getImagesFromNet(request.terminallistResult.result, appDefault.getUserkey());
                    mReceiver.send(SUCCESS, null);
                    return;
                } catch (IOException e) {
                    //网络异常，3秒后继续联网
                } catch (Exception e) {
                    e.printStackTrace();
                    break;//其他异常，不应该继续联网了
                }
            }
            if (++count == 5) {
                break;
            }
            SystemClock.sleep(3000);//尝试5次，如果还没有成功，就退出
        }
    }


    static class FirstRequest extends MultiRequest {
        private static final int STEP_LOGIN = 1;
        private static final int STEP_TERMINALLIST = 2;
        private static final int STEP_TERMINALINFO = 3;
        private static final int STEP_TERMINALCONFIG = 4;
        private static final int STEP_NEW_TERMINALCONFIG = 5;
        private int step;
        private int index;
        AppDefault appDefault;

        String userid;
        String userKey;

        public LoginResult loginResult;
        public TerminallistResult terminallistResult;
        public QueryUserTerminalInfoResult terminalInfoResult;
        public TerminalConfigResult[] configs;
        public AllTerminalConfig[] newConfigs;


        public FirstRequest() {
            appDefault = new AppDefault();
            step = STEP_LOGIN;
            String bbtreeUserid = appDefault.getBbtreeUserid();
            String bbtreeUserPhoneNumber = appDefault.getBbtreeUserPhoneNumber();
            String json = GsonFactory.newInstance().toJson(new GetAccessToken(bbtreeUserid, bbtreeUserPhoneNumber));
            newRequest(json);
        }

        @Override
        protected void onResponse(String str) {
//            MyLogger.jLog().i(str);
            Gson gson = GsonFactory.newInstance();
            switch (step) {
                case STEP_LOGIN:
                    loginResult = gson.fromJson(str, LoginResult.class);
                    if (loginResult.code != 0) {//密码错误，直接抛出异常
                        throw new RuntimeException();
                    }

                    userid = loginResult.result.userid;
                    userKey = loginResult.result.userkey;
                    step = STEP_TERMINALLIST;
                    String terminallist = gson.toJson(new TerminalListParams(loginResult.result.userkey, loginResult.result.userid));
                    newRequest(terminallist);
                    break;
                case STEP_TERMINALLIST:
                    terminallistResult = gson.fromJson(str, TerminallistResult.class);
                    if (terminallistResult.code != 0) {
                        throw new RuntimeException();
                    }


                    if (terminallistResult.result.size() != 0) {//绑定有手表
                        StringBuilder builder = new StringBuilder();
                        for (TerminallistResult.Terminal item : terminallistResult.result) {
                            builder.append(item.userterminalid).append(",");
                        }
                        builder.deleteCharAt(builder.length() - 1);

                        step = STEP_TERMINALINFO;
                        String info = gson.toJson(new QueryUserTerminalInfoParams(userKey, builder.toString()));
                        newRequest(info);
                    }
                    break;
                case STEP_TERMINALINFO:
                    terminalInfoResult = gson.fromJson(str, QueryUserTerminalInfoResult.class);
                    if (terminalInfoResult.code != 0) {
                        throw new RuntimeException();
                    }

                    //继续获取terminalconfig
                    step = STEP_TERMINALCONFIG;
                    configs = new TerminalConfigResult[terminallistResult.result.size()];
                    String terminalid = terminallistResult.result.get(0).terminalid;
                    String terminalConfig = gson.toJson(new TerminalConfigParams(userKey, terminalid));
                    newRequest(terminalConfig);
                    break;
                case STEP_TERMINALCONFIG:
                    configs[index] = gson.fromJson(str, TerminalConfigResult.class);
                    if (configs[index].code != 0) {
                        throw new RuntimeException();
                    }

                    index++;
                    if (index != configs.length) {//还没有获取完毕
                        String id = terminallistResult.result.get(index).terminalid;
                        String s = gson.toJson(new TerminalConfigParams(userKey, id));
                        newRequest(s);
                    }
                    break;
                    /*else {
                        //已经获取完毕，继续获取newTerminalConfig
                        index = 0;
                        step = STEP_NEW_TERMINALCONFIG;*/
//                        newConfigs = new AllTerminalConfig[terminallistResult.result.size()];
//                        String s = gson.toJson(new GetAllTerminalConfig(configs[0].result.imei));
//                        newRequest(s);
                  /*  }
                    break;*/
//                case STEP_NEW_TERMINALCONFIG:
//                    newConfigs[index] = gson.fromJson(str,AllTerminalConfig.class);
//                    if (newConfigs[index].code!=0){
//                        throw new RuntimeException();
//                    }
//
//                    index++;
//                    if (index!=newConfigs.length){
//                        String s = gson.toJson(new GetAllTerminalConfig(configs[index].result.imei));
//                        newRequest(s);
//                    }
//                    break;
            }

        }
    }

    private void save(FirstRequest request, AppDefault appDefault) {
        LoginResult.Data result = request.loginResult.result;
        appDefault.setUserid(result.userid);
        appDefault.setUserkey(result.userkey);
        appDefault.setProducts(result.products);
        appDefault.setDisplayUsername(result.nickname);
        appDefault.setApiUsername(result.username);

        List<TerminallistResult.Terminal> terminals = request.terminallistResult.result;


        if (terminals != null && !terminals.isEmpty()) {//绑定手表有可能为空，没有继续获取terminalinfo
            List<QueryUserTerminalInfoResult.Data> infoResult = request.terminalInfoResult.result;

            UserDefault userDefault = new UserDefault(result.userid);
            userDefault.setTerminals(terminals);
            int count = terminals.size();

            for (int i = 0; i < count; i++) {
                TerminallistResult.Terminal terminal = terminals.get(i);

                TerminalDefault terminalDefault = new TerminalDefault(terminal.terminalid);
                terminalDefault.setConfig(request.configs[i].result);
//                terminalDefault.setNewConfig(request.newConfigs[i].result);
//                terminalDefault.setSilenceCount(String.valueOf(terminal.icon.silence));
//                terminalDefault.setAlarmCount(String.valueOf(terminal.icon.alarm));
//                terminalDefault.setFencingCount(String.valueOf(terminal.icon.fencing));
//                terminalDefault.setDetachNoticeCount(String.valueOf(terminal.icon.d));

                UserTerminalDefault userTerminalDefault = new UserTerminalDefault(terminal.userterminalid);
                userTerminalDefault.setInfo(infoResult.get(i));

            }
        } else {
            new UserDefault(result.userid).setTerminals(null);

        }

    }

    private void getImagesFromNet(List<TerminallistResult.Terminal> result, String userkey) {
        MyLogger.kLog().i("getImagesFromNet========WX");
        File file = new File(Constants.ICON_PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        String serverIp = new SocketAddressSwitcher(getFilesDir() + "/server_config").getServerAddress().ip;
        String iconPath = null;
        for (TerminallistResult.Terminal item : result) {
            UserTerminalDefault userTerminalDefault = new UserTerminalDefault(item.userterminalid);
            iconPath = userTerminalDefault.getIconPath();
            if (iconPath == null) {//联网获取
                String newImagePath = Constants.ICON_PATH + "/" + UUID.randomUUID().toString() + ".png";
                loadPic(userkey, item.terminalid, item.userterminalid, newImagePath, serverIp, userTerminalDefault);
            } else {
                if (!new File(iconPath).exists()) {//图片被删掉了
                    loadPic(userkey, item.terminalid, item.userterminalid, iconPath, serverIp, userTerminalDefault);
                }
            }
        }
    }

    private void loadPic(String userkey, String terminalid, String userterminalid, String path, String ip, UserTerminalDefault userTerminalDefault) {

        int code = new LoadPicCommand(userkey, userterminalid, path, ip).execute();
        switch (code) {
            case BaseCommand.STATUS_OK:
                userTerminalDefault.setIconPath(path);
                break;
            case -1://用户没有上传过头像
                int gender = userTerminalDefault.getInfo().gender;
                String imei = new TerminalDefault(terminalid).getConfig().imei;
                Controller.getInstance().setCidMode(imei);
                if (!Controller.getInstance().isOldMainMode()) {
                    if (gender == 1) {
                        userTerminalDefault.setIconPath(AppDefault.getBoyIconPath(this));
                    } else if (gender == 2) {
                        userTerminalDefault.setIconPath(AppDefault.getGirlIconPath(this));
                    } else {
                        userTerminalDefault.setIconPath(AppDefault.getDefaultIconPath(this));
                    }
                } else {
                    if (gender == 1) {
                        userTerminalDefault.setIconPath(AppDefault.getBoyIconPathOldMan(this));
                    } else if (gender == 2) {
                        userTerminalDefault.setIconPath(AppDefault.getGirlIconPathOldMan(this));
                    } else {
                        userTerminalDefault.setIconPath(AppDefault.getDefaultIconPathOldMan(this));
                    }
                }

                break;
            case -2://网络错误，下次还接着下载

                break;
        }
    }

}
